<template>
  <section>
    <form class="grid gap-y-3">
      <div class="rounded-lg">
        <input type="text" placeholder="Your Name" class="w-full rounded" v-model="data.name" />
      </div>
      <div>
        <input type="text" placeholder="Company" class="w-full rounded" v-model="data.company" />
      </div>
      <div>
        <input type="text" placeholder="Email" class="w-full rounded" v-model="data.email" />
      </div>
      <div>
        <input type="text" placeholder="Phone Number" class="w-full rounded" v-model="data.phone" />
      </div>
      <div>
        <input type="text" placeholder="Country" class="w-full rounded" v-model="data.country" />
      </div>
      <div>
        <input
          type="file"
          ref="fileInput"
          accept=".stl, .step, .igs, .stp, .iges, .sldprt, .x_t, .zip"
          @change="handleFileChange"
        />
      </div>
      <div>
        <textarea
          type="text"
          placeholder="Message Please tell us what you need.Upload File ( 3D model files: .stl, .step, .igs, .stp, .iges, .sldprt, .x_t, .zip, .rar etc.)"
          class="w-full rounded h-44"
          v-model="data.message"
        />
      </div>
      <div class="flex flex-col">
        <label class="h-9 flex items-center" for="CaptchaCode">
          <span>Captcha Code: </span>
          <span class="ml-2 text-5 leading-9 font-bold"> {{ captcha }} </span>
          <button
            type="button"
            class="ml-2 font-bold text-xl text-[#99020c] leading-9"
            @click="generateCaptcha()"
          >
            ⟳
          </button>
        </label>
        <input
          type="text"
          id="CaptchaCode"
          placeholder="Captcha Code"
          class="rounded"
          v-model="userInputCaptcha"
        />
      </div>
      <button class="default-button rounded" type="button" @click="handleSubmit()">Submit</button>
    </form>
  </section>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'

const fileInput = ref(null)

const data = ref({
  name: '',
  company: '',
  email: '',
  phone: '',
  country: '',
  modelUrl: '',
  message: ''
})

const captcha = ref() // 三位数验证码
const userInputCaptcha = ref('') // 用户输入的验证码
const validationMessage = ref('')

// 工具方法：生成三位数验证码
function generateCaptcha() {
  captcha.value = Math.floor(100 + Math.random() * 900).toString()
}

// 验证输入是否正确
function validateCaptcha() {
  if (userInputCaptcha.value === captcha.value) {
    validationMessage.value = '验证成功！'
    return true
  } else {
    validationMessage.value = '验证码错误，请重试。'
    return false
  }
}

const baseUrl = import.meta.env.VITE_APP_BASE_API
const baseAuthorization = import.meta.env.VITE_APP_AUTHORIZATION_TOKEN

const selectedFile = ref(null)

// 处理文件改变
const handleFileChange = async (event) => {
  const file = event.target.files?.[0]
  if (file) {
    selectedFile.value = file

    const formData = new FormData()
    formData.append('file', selectedFile.value)

    try {
      // 调用上传接口
      const res = await axios.post(baseUrl + '/common/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'authorization': baseAuthorization
        }
      })
      if (res.data.code === 200) {
        data.value.modelUrl = res.data.fileName
      }
    } catch (error) {
      console.error(error)
      alert('文件上传失败，请重试。')
    }
  }
}

// 处理提交
const handleSubmit = async () => {
  if (validateCaptcha()) {
    // axios发送post请求
    try {
      const response = await axios.post(baseUrl + '/web/contact', data.value, {
        headers: {
          'authorization': baseAuthorization
        }
      })
      if (response.data.code === 200) {
        alert('提交成功！')
      } else {
        alert(response.data.msg)
      }
    } catch (error) {
      console.error(error)
      alert('提交失败，请重试。')
    } finally {
      resetData()
      generateCaptcha()
    }
  } else {
    // 弹出提示
    alert(validationMessage.value)
    generateCaptcha()
  }
}

// 重置data
const resetData = () => {
  fileInput.value.value = ''
  data.value = {
    name: '',
    company: '',
    email: '',
    phone: '',
    country: '',
    modelUrl: '',
    message: ''
  }
  userInputCaptcha.value = ''
}

onMounted(() => {
  generateCaptcha()
})
</script>
<style scoped>
section {
  --primary-color: #c00000;
}

.default-button {
  color: #ffffff;
  background-color: var(--primary-color);
  height: 2.5rem;
}

input:focus {
  outline: none;
  border: 2px solid var(--primary-color);
  box-shadow: none;
}

textarea:focus {
  outline: none;
  border: 2px solid var(--primary-color);
  box-shadow: none;
}
</style>
